<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<%@ include file="../common.jsp"%>
<%@ page import="org.springside.core.Constants,cn.firstsoft.firstframe.admin.*"%>
<%@ page import="java.io.*,java.util.*,org.jdom.*,org.jdom.input.*,org.jdom.output.*" %>
<%@ page import="java.sql.*,javax.sql.*,javax.naming.*" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>管理控制台 - 数据中心</title>
<%@ include file="/common/meta2.jsp"%>
<link href="../style.css" type="text/css" rel=stylesheet>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<%
	String id = request.getParameter("id");
	if (id == null) id = "";
	String name = new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
	if (name == null) name = "";
	String dbname = request.getParameter("dbname");
	if (dbname == null) dbname ="";
	String dbtype = request.getParameter("dbtype");
	if (dbtype == null) dbtype = "";
	String datasource = request.getParameter("datasource");
	if (datasource == null) datasource = "";

	String dbauser = request.getParameter("dbauser");
	if (dbauser == null) dbauser = "";
	
	String dbapassword = request.getParameter("dbapassword");
	if (dbapassword == null) dbapassword = "";	
	
	String dbuser = request.getParameter("dbuser");
	if (dbuser == null) dbuser = "";
	if ("sqlserver".equals(dbtype)) dbuser = dbauser;
	
	String dbpassword = request.getParameter("dbpassword");
	if (dbpassword == null) dbpassword = "";
	if ("sqlserver".equals(dbtype)) dbpassword = dbapassword;
	
	String dbsize = request.getParameter("dbsize");
	if (dbsize == null) dbsize = "500";
	
	String dbdir = request.getParameter("dbdir");
	if (dbdir == null) dbdir = "";		
			
	String maindir = request.getParameter("maindir");
	if (maindir == null) maindir = "";
	int error_code = 0;
	boolean sqluser = false;
	
	//检查数据库的连接，使用jdbc的方式，同时检查用户或者数据库是否存在
	Connection conn = null;
	Statement stmt = null ;
	ResultSet rs = null; 
	
	if ("sqlserver".equals(dbtype)) {
		try { 
			//注册数据库驱动程序为oracle驱动 
			Class.forName("net.sourceforge.jtds.jdbc.Driver"); 
			conn = DriverManager.getConnection( 
				"jdbc:jtds:sqlserver://"+datasource+";DatabaseName=master", dbauser, dbapassword);
			stmt = conn.createStatement(); 
			
			rs = stmt.executeQuery("select * from sysdatabases where name = '"+dbname+"'");
			if (rs.next()) {
				//判断说明此用户已经存在了
				error_code = 2;
				out.println("要定义的数据库用户已经存在！");
			}
			rs.close();
			if (!"sa".equalsIgnoreCase(dbname)) {
				rs = stmt.executeQuery("select * from sysusers where status=2 and name = '"+dbname+"'");
				if (rs.next()) {
					sqluser = true;
					//sql server的用户存在，不用创建了

				}
				rs.close();
			} else {
				sqluser = true;
			}
			stmt.close();
			conn.close();
			// 
		} catch (Exception e) { 
			//这样写是为了方便调试程序，出错打印mydb()就知道在什么地方出错了 
			System.err.println(e.getMessage());
			out.println(e.getMessage());
			//数据库连接不对

			error_code = 1; 
			out.println("数据库链接不正确！");
		} finally {
			try {
				if (rs != null) rs.close();
				if (stmt != null) stmt.close();
				if (conn != null) conn.close();
			} catch (Exception e) { 
				System.err.println(e.getMessage());
				out.println(e.getMessage());			
			}
		}		
	} else if ("oracle".equals(dbtype)) {
		try { 
			//注册数据库驱动程序为oracle驱动 
			Class.forName("oracle.jdbc.OracleDriver"); 
			conn = DriverManager.getConnection( 
				"jdbc:oracle:thin:@" + datasource + ":"+ dbname, dbauser, dbapassword);
			stmt = conn.createStatement(); 
			
			//查找TABLESPACES是否存在
			rs = stmt.executeQuery("select * from user_tablespaces where lower(tablespace_name) = '"+id.toLowerCase()+"_data' or lower(tablespace_name) = '" + id + "_temp'");
			if (rs.next()) {
				//判断说明此用户已经存在了
				error_code = 2;
				out.println("数据库的表空间已经存在，不能创建！");
			}
			rs.close();			
			
			rs = stmt.executeQuery("select * from all_users where lower(username) = '"+dbuser.toLowerCase()+"'");
			if (rs.next()) {
				//判断说明此用户已经存在了
				error_code = 2;
				out.println("要定义的数据库用户已经存在！");
			}
			rs.close();
			
			
			
			stmt.close();
			conn.close();
			// 
		} catch (Exception e) { 
			//这样写是为了方便调试程序，出错打印mydb()就知道在什么地方出错了 
			System.err.println(e.getMessage());
			out.println(e.getMessage());
			//数据库连接不对

			error_code = 1; 
			out.println("数据库链接不正确！");
		} finally {
			try {
				if (rs != null) rs.close();
				if (stmt != null) stmt.close();
				if (conn != null) conn.close();
			} catch (Exception e) { 
				System.err.println(e.getMessage());
				out.println(e.getMessage());			
			}
		}
	}
	
	//检查数据源是否重复
	if (error_code == 0) {
		//校验，合法性检查，根据安装类型和应用服务器类型判断
		String xmlFile = "";
		if ("TOMCAT".equals(Environment.getWebServerName())) { 
			xmlFile = Environment.getWebServerPath() + File.separator + "conf" + File.separator + "server.xml";
		} else if ("APUSIC".equals(Environment.getWebServerName())) {
			xmlFile = Environment.getWebServerPath() + File.separator + "config" + File.separator + "datasources.xml";
		} else {
			xmlFile = "unknown";
		}	
		System.out.println(xmlFile);	
		File file = new File(xmlFile);
		
		if (file.exists()) {
			SAXBuilder builder = new SAXBuilder();
			Document doc;
			try {
				if ("TOMCAT".equals(Environment.getWebServerName())) { 
					doc = builder.build(file);
					Element server = doc.getRootElement();
					Element service = server.getChild("Service");
					Element engine = service.getChild("Engine");
					Element host = engine.getChild("Host");
					Element context = host.getChild("Context");
					List resourceList = context.getChildren("Resource");
					
					for (int i=0; i<resourceList.size(); i++) {
						Element resource = (Element)resourceList.get(i);
						//判断是否已经有这个名字了
						String jndi_name = resource.getAttributeValue("name");
						
						if (jndi_name.equalsIgnoreCase("jdbc/"+id)) {
							//错误编号1，这个数据源名字已经被用了

							error_code = 3;
							out.println("此数据源已经在数据源定义中存在，需要先删除此定义！");
							break;
						}
					}
				} else if ("APUSIC".equals(Environment.getWebServerName())) {
					doc = builder.build(file);
					Element datasources = doc.getRootElement();
					List resourceList = datasources.getChildren("datasource");
				
					for (int i=0; i<resourceList.size(); i++) {
						Element resource = (Element)resourceList.get(i);	
						String jndi_name = resource.getAttributeValue("jndi-name");
						
						if (jndi_name.equalsIgnoreCase("jdbc/"+id)) {
							//错误编号1，这个数据源名字已经被用了

							error_code = 3;
							out.println("此数据源已经在数据源定义中存在，需要先删除此定义！");
							break;
						}	
					}									
				} else {
					//什么也不做
				}
			} catch (JDOMException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			//错误编号2，目标文件不存在
			error_code = 4;
			out.println("没有找到数据源文件！");
		}
	}

	String dataZip = System.getProperty("oa_application.config") + File.separator + "data.zip";
	
	//检查输入的目录下是否已经有目录存在了

	if (error_code == 0) {
	
		File dataZipFile = new File(dataZip);
		
		File maindirFile = new File(maindir);
		if (!maindirFile.exists()) {
			maindirFile.mkdirs();
		} else {
			if (maindirFile.isDirectory() && maindirFile.listFiles().length>0) {
				//判断是否正在使用的目录，表示这个目录已经使用
				error_code = 11;
				out.println("当前指定的目录已经被使用，不能创建数据目录");
			} else {
				//是否空目录

			}
		}
		if (error_code == 0) {
			if (dataZipFile.exists()) {
				//什么不做

			} else {
				error_code = 10;
				out.println("<br>数据目录模板包不存在！");
			}
		}
	}
	
	if (error_code == 0) {
		//创建数据库

		if ("sqlserver".equals(dbtype)) {
			try { 
				//注册数据库驱动程序为oracle驱动 
				Class.forName("net.sourceforge.jtds.jdbc.Driver"); 
				conn = DriverManager.getConnection( 
					"jdbc:jtds:sqlserver://"+datasource+";DatabaseName=master", dbauser, dbapassword);
				stmt = conn.createStatement(); 
				
				String sql = "CREATE DATABASE " + id + "\n" + 
						"ON \n" + 
						"( NAME = " + id + "_Data,\n" +
						"   FILENAME = '" + dbdir + File.separator + id + "_Data.mdf',\n" +
						"   SIZE = " + dbsize + "MB,\n" +
						"   MAXSIZE = UNLIMITED,\n" +
						"   FILEGROWTH = 10% )\n" +
						"LOG ON\n" +
						"( NAME = '" + id + "_Log',\n" +
						"   FILENAME = '" + dbdir + File.separator + id + "_Log.ldf',\n" +
						"   SIZE = 5MB,\n" +
						"   MAXSIZE = 200MB,\n" +
						"   FILEGROWTH = 10% )\n";
				out.println("创建的sql: "+ sql);
				stmt.execute(sql);
				
				//执行sql语句 --
				//参照EAS的sql处理办法------------------
				
				
				stmt.close();
				//创建表及插入初始化数据

				conn.close();
				// 
			} catch (Exception e) { 
				//这样写是为了方便调试程序，出错打印mydb()就知道在什么地方出错了 
				System.err.println(e.getMessage());
				out.println(e.getMessage());
				//数据库连接不对

				error_code = 1; 
				out.println("数据库链接不正确！");
			} finally {
				try {
					if (rs != null) rs.close();
					if (stmt != null) stmt.close();
					if (conn != null) conn.close();
				} catch (Exception e) { 
					System.err.println(e.getMessage());
					out.println(e.getMessage());			
				}
			}		
		} else if ("oracle".equals(dbtype)) {
			try { 
				//注册数据库驱动程序为oracle驱动 
				Class.forName("oracle.jdbc.OracleDriver"); 
				conn = DriverManager.getConnection( 
					"jdbc:oracle:thin:@" + datasource + ":"+ dbname, dbauser, dbapassword);
				stmt = conn.createStatement(); 
				
				String sql = "CREATE TABLESPACE "+id+"_DATA DATAFILE \n" +
  					"'"+dbdir + "/" +  id +"_DATA.DBF' SIZE " + dbsize + "M AUTOEXTEND OFF \n" +
					"LOGGING \n" +
					"PERMANENT \n" +
					"EXTENT MANAGEMENT LOCAL AUTOALLOCATE \n" +
					"BLOCKSIZE 8K \n" +
					"SEGMENT SPACE MANAGEMENT MANUAL \n" +
					"FLASHBACK ON";
					
				out.println("创建数据表空间sql：" + sql);
				stmt.execute(sql);

				sql = "CREATE TEMPORARY TABLESPACE "+id+"_TEMP TEMPFILE \n" +
  					"'" + dbdir + "/" + id + "_TEMP.DBF' SIZE 100M AUTOEXTEND OFF \n" +
					"TABLESPACE GROUP '' \n" +
					"EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M";
				out.println("<br>创建临时表空间sql：" + sql);	
				stmt.execute(sql);
				
				sql = "CREATE USER "+dbuser+" PROFILE DEFAULT \n" + 
    				"IDENTIFIED BY "+dbpassword+" DEFAULT TABLESPACE \n" + 
    				id + "_DATA \n" + 
    				"TEMPORARY TABLESPACE " + id + "_TEMP \n" +
    				"ACCOUNT UNLOCK";
				out.println("<br>创建用户sql：" + sql);	
				stmt.execute(sql);

				sql = "GRANT DBA TO " + dbuser;	
				
				out.println("<br>用户授权sql：" + sql);
				stmt.execute(sql);
				
				//执行sql语句 --
				//参照EAS的sql处理办法------------------
								
				stmt.close(); 					
				conn.close();
				// 
			} catch (Exception e) { 
				//这样写是为了方便调试程序，出错打印mydb()就知道在什么地方出错了 
				System.err.println(e.getMessage());
				out.println(e.getMessage());
				//数据库连接不对

				error_code = 1; 
				out.println("数据库链接不正确！");
			} finally {
				try {
					if (rs != null) rs.close();
					if (stmt != null) stmt.close();
					if (conn != null) conn.close();
				} catch (Exception e) { 
					System.err.println(e.getMessage());
					out.println(e.getMessage());			
				}
			}
		}
	}
	
	if (error_code == 0) {
		ZipUtil.unZip(dataZip, maindir);
	}
%>
<% if (error_code > 0) { %>
<form name="createForm" action="create.jsp" method="post">
<% } else { %>
<form name="createForm" action="register.jsp" method="post">
<% } %>
<input type="hidden" name="action" value="save">
<input type="hidden" name="id" value="<%=id %>">
<input type="hidden" name="name" value="<%=name %>">
<input type="hidden" name="dbname" value="<%=dbname %>">
<input type="hidden" name="dbtype" value="<%=dbtype %>">
<input type="hidden" name="datasource" value="<%=datasource %>">
<input type="hidden" name="dbauser" value="<%=dbauser %>">
<input type="hidden" name="dbapassword" value="<%=dbapassword %>">
<input type="hidden" name="dbuser" value="<%=dbuser %>">
<input type="hidden" name="dbpassword" value="<%=dbpassword %>">
<input type="hidden" name="dbsize" value="<%=dbsize %>">
<input type="hidden" name="dbdir" value="<%=dbdir %>">
<input type="hidden" name="maindir" value="<%=maindir %>">
<table width="100%">
  <% if (error_code > 0) { %>
  <tr>
  	<td width="100%">
  	  错误编号：<%=error_code %>，由于数据的错误不能正常创建数据库，
  	  <input type="submit" name="register" 
  	    value="&nbsp;返回上一步&nbsp;">	    
  	</td>
  </tr>  
  <% } else { %>
  <tr>
  	<td width="100%">
	新数库创建完成！下一步注册数据中心!
  	  <input type="submit" name="register" 
  	    value="&nbsp;下一步注册&nbsp;"">		    
  	</td>
  </tr>   
  <% } %>
</table>
</form>
</body>
</html>
